import {getInfoApi, loginApi, loginOutApi} from '@/api/user'
import {Route} from '@/router/index.type'
import {ActionContext} from 'vuex'

export interface userState {
	token: string,
	info: object,
	menu: Route[],
}

const state = (): userState => ({
	token: '', // 登录token
	info: {},  // 用户信息
	menu: []  // 用户菜单
})

// getters
const getters = {
	token(state: userState) {
		return state.token
	}
}

// mutations
const mutations = {
	tokenChange(state: userState, token: string) {
		state.token = token
	},
	infoChange(state: userState, info: object) {
		state.info = info
	},
	menuChange(state: userState, menu: Route[]) {
		state.menu = menu
	}
}

// actions
const actions = {
	// login by login.vue
	login({commit, dispatch}: ActionContext<userState, userState>, params: any) {
		return new Promise((resolve, reject) => {
			loginApi(params)
				.then(res => {
					commit('tokenChange', res.data.token)
					dispatch('getInfo')
						.then(info => {
							resolve(res.data.token)
						})
				}).catch(err => {
				reject(err)
			})
		})
	},
	// get user info after user logined
	getInfo({commit, dispatch}: ActionContext<userState, userState>) {
		return new Promise((resolve, reject) => {
			getInfoApi()
				.then(res => {
					commit('menuChange', res.data.menuData)
					commit('infoChange', res.data.userData)
					resolve(res)
				}).catch(err => {
				dispatch('loginOut').then(() => {
					location.reload()
				})
			})
		})
	},

	// login out the system after user click the loginOut button
	loginOut({commit}: ActionContext<userState, userState>) {
		loginOutApi()
			.then(res => {
			})
			.catch(error => {
			})
			.finally(() => {
				localStorage.removeItem('tabs')
				localStorage.removeItem('vuex')
				sessionStorage.removeItem('vuex')
				location.reload()
			})
	}
}

export default {
	namespaced: true,
	state,
	actions,
	getters,
	mutations
}
